/**
 * 
 */
package org.lookouster.nextAgadir.pointageBureau.ui;

/**
 * @author Lookouster
 *
 */


	import java.awt.*;
	import java.awt.event.*;
	import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

	import java.beans.*;
import java.io.File;
import java.util.ArrayList;
	import java.util.Random;
import org.lookouster.nextAgadir.pointageBureau.bases.*;
import org.lookouster.nextAgadir.pointageBureau.outils.BDFunctions;
import org.lookouster.nextAgadir.pointageBureau.outils.Commons;
import org.lookouster.nextAgadir.pointageBureau.outils.Dynamic;
import org.lookouster.nextAgadir.pointageBureau.outils.functions;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

	public class ExportChpXML extends JDialog 
	{

	    private JProgressBar progressBar;
	    private Task task;
	    private JLabel infos;
	    

	    class Task extends SwingWorker<Void, Void> {
	        /*
	         * Main task. Executed in background thread.
	         */
	        @Override
	        public Void doInBackground() {
	            int progress = 0;
	            //Initialize progress property.
	            setProgress(0);
	            buildXMLOutput();
	            setProgress(100);
	            return null;
	        }

	        /*
	         * Executed in event dispatching thread
	         */
	        @Override
	        public void done() {
	            Toolkit.getDefaultToolkit().beep();
	            
	            setCursor(null); //turn off the wait cursor
	            
	        }
	    }
	    
	    
	    
	    public ExportChpXML(java.awt.Frame parent, boolean modal) {
	    	super(parent, modal);
	    	
	        this.setTitle(UICommons.genBDChp);
	        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
	        infos=new JLabel(UICommons.exp);
	        infos.setPreferredSize(new Dimension(250,20));
	        progressBar = new JProgressBar(0, 100);
	        progressBar.setValue(0);
	        progressBar.setIndeterminate(true);
	        progressBar.setStringPainted(true);
	        //progressBar.setString(UICommons.BChpDB);

	        

	        JPanel panel = new JPanel();
	        panel.setOpaque(true);
	        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
	        panel.add(progressBar);
	        panel.add(infos);
	        getContentPane().add(panel, BorderLayout.PAGE_START);
	        pack();
	        
	        //Actions
	        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
	        task = new Task();
	        task.execute();
	        progressBar.setIndeterminate(false);
	        
	        //progressBar.setVisible(false);
	        
	        
	    }

	    



	    public static void main(String[] args) {
	        //Schedule a job for the event-dispatching thread:
	        //creating and showing this application's GUI.
	        javax.swing.SwingUtilities.invokeLater(new Runnable() {
	            public void run() {
	                new ExportChpXML(null,true).setVisible(true);
	            }
	        });
	    }
	    
	    public void buildXMLOutput()
	    {
	    	try {
				java.util.List<Ferme> fermes=BDFunctions.getFermesList();
				if(fermes==null)
				{
					JOptionPane.showMessageDialog(this, UICommons.bdChpEmty);
		        	this.setVisible(false);
		        	return;
				}
					
				Document doc=null;
				DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
				DocumentBuilder docBuilder=dbFactory.newDocumentBuilder();
				
				//Create new Document
				doc=docBuilder.newDocument();
				doc.setXmlStandalone(true);
				//root: champs
				Element root=doc.createElement(Commons.STRChp);
				for(Ferme f:fermes)
				{
					Element ferme=doc.createElement(Dynamic.STRN0);
					ferme.appendChild(doc.createTextNode(f.getNomEspaceTravail()));
					//Create attribute
					ferme.setAttribute(Commons.attrId, String.valueOf(
							f.getIdEspaceTravail()));
					//ferme.setAttribute(Commons.attrName, f.getNomEspaceTravail());
					//Bind to root
					root.appendChild(ferme);
					if(f.getSecteurs()!=null)
					{
						java.util.List<Secteur> secteurs=new ArrayList<Secteur>(
								f.getSecteurs());
						for(Secteur st:secteurs)
						{
							Element secteur=doc.createElement(Dynamic.STRN1);
							//Bind to ferme
							ferme.appendChild(secteur);
							secteur.appendChild(doc.createTextNode(
									st.getNomEspaceTravail()));
							//Create attribute
							secteur.setAttribute(Commons.attrId, String.valueOf(
									st.getIdEspaceTravail()));
							/*secteur.setAttribute(Commons.attrName, 
									st.getNomEspaceTravail());*/
							if(st.getSerres()==null)
								continue;
							java.util.List<Serre> serres=new ArrayList<Serre>(
									st.getSerres());
								for(Serre sr:serres)
								{
									Element serre=doc.createElement(Dynamic.STRN2);
									serre.appendChild(doc.createTextNode(
											sr.getNomEspaceTravail()));
									//Create attribute
									serre.setAttribute(Commons.attrId, 
											String.valueOf(sr.getIdEspaceTravail()));
									/*serre.setAttribute(Commons.attrName, 
											sr.getNomEspaceTravail());*/
									//Bind to secteur
									secteur.appendChild(serre);
									if(sr.getBillons()!=null)
									{
										java.util.List<Billon> billons=
											new ArrayList<Billon>(sr.getBillons());
									
											for(Billon b:billons)
											{
												Element billon=doc.createElement(
														Dynamic.STRN3);
												billon.appendChild(doc.createTextNode(
														b.getNomEspaceTravail()));
												//Create attribute
												billon.setAttribute(Commons.attrId,
													String.valueOf(b.getIdEspaceTravail()));
												/*billon.setAttribute(Commons.attrName,
														b.getNomEspaceTravail());*/
												//Bind to serre
												serre.appendChild(billon);
											}
									}
									
								}
						}
					}
					
					
						
					
					//functions.affiche(ferme.toString());	
				}
				infos.setText(UICommons.expSuc);
				progressBar.setValue(100);
				JFileChooser chooseDir=new JFileChooser();
				chooseDir.setApproveButtonText("Enregistrer...");
				int returnVal = chooseDir.showOpenDialog(this);
				chooseDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				chooseDir.setDialogType(JFileChooser.SAVE_DIALOG);
				String fileName="Commons.DBChpFile";
				if(returnVal==JFileChooser.APPROVE_OPTION)
				{
					File rep = chooseDir.getSelectedFile();
					fileName=rep.getAbsolutePath();
					doc.appendChild(root);
					TransformerFactory xformFactory=TransformerFactory.newInstance();
					Transformer idTransform=xformFactory.newTransformer();
					Source input=new DOMSource(doc);
					Result output=new StreamResult(fileName+Commons.DBChpFileExt);
					idTransform.transform(input, output);
					this.setVisible(false);
				}
							
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				JOptionPane.showMessageDialog(this, UICommons.errBDCon);
	        	this.setVisible(false);
			}
	    	
	    }
}
	
	
	
